package main

import (
	"bufio"
	"learn/learn/socket/internal/protocol"
	"net"
	"os"
	"strings"
)

func main() {
	var (
		conn net.Conn
		err  error
	)
	defer func() {
		if err != nil {
			println(err.Error())
		}
	}()
	conn, err = net.Dial("tcp", "127.0.0.1:9000")
	if err != nil {
		return
	}
	input := bufio.NewReader(os.Stdin)
	for {
		var (
			cErr   error
			resStr string
			res    [125]byte
			n      int
		)
		defer func() {
			if cErr != nil {
				println(err.Error())
			}
		}()
		resStr, cErr = input.ReadString('\n')
		if err != nil {
			break
		}
		str := strings.Trim(resStr, "\r\n")
		if strings.ToUpper(str) == "Q" {
			return
		}
		_, cErr = conn.Write(protocol.EnPack([]byte(str)))
		if err != nil {
			return
		}
		read := bufio.NewReader(conn)
		n, cErr = read.Read(res[:])
		if err != nil {
			return
		}
		println(string(res[:n]))
	}
}
